<template>
  <n-upload
    action="https://xunjinasd.oss-cn-hangzhou.aliyuncs.com"
    :on-before-upload="handleBeforeUpload"
    :data="params"
    :on-finish="handleUploadFinish"
    :defaultFileList="modelValue"
    @update:file-list="handleUpdateFileList"
    v-bind="$attrs"
  >
    <!-- <n-button v-if="!readonly" type="primary" secondary
      >上传文件(不能超过{{ descriptionFileSize }}MB,支持格式为:
      {{ descriptionFileType?.join() }})</n-button
    > -->
    <n-button
      v-if="submitText"
      type="primary"
      secondary
      stronger
      size="small"
      style="width: 200px"
      >{{ submitText }}</n-button
    >
    <slot v-else></slot>
  </n-upload>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { getUploadparams, uploadOssApi, addSpace } from "@/api/upload";
import { v1 } from "uuid";
const files = ref([]);
const params = ref({});
const props = defineProps({
  submitText: String,
  modelValue: {
    type: Array<any>,
    defaut: () => {
      return [];
    },
  },
});
const emits = defineEmits(["update:modelValue"]);
const getExtension = (fileName: string) => {
  const lastDotIndex = fileName.lastIndexOf(".");

  // 检查是否有后缀名
  return lastDotIndex >= 0 ? fileName.substring(lastDotIndex + 1) : "";
};
const handleBeforeUpload = async ({ file }) => {
  const paramsData = await getUploadparams();
  console.log(paramsData, file);

  params.value = {
    ...paramsData["data"],
    key: `qa/${v1()}.${getExtension(file.name)}`,
  };
};

const handleUploadFinish = ({ file }) => {
  console.log(`upload finish`, file);
  addSpace(params.value["host"], params.value["key"], file);
  file.url = `${params.value["host"]}/${params.value["key"]}`;
  // emits("update:modelValue", [
  //   ...props.modelValue,
  //   {
  //     id: file.id,
  //     name: file.name,
  //     url: `${params.value["host"]}/${params.value["key"]}`,
  //     status: "finished",
  //   },
  // ]);
  // setTimeout(() => {
  //   console.log(files.value);
  // }, 100);
  return file;
  // formData.value.files.push({
  //   url: `${params.value["host"]}/${params.value["key"]}`,
  // });
};
const handleUpdateFileList = (list) => {
  console.log(list);
  emits("update:modelValue", list);
};
onMounted(() => {
  // if (props.modelValue) {
  //   alert();
  //   props.modelValue.forEach((item) => {
  //     item.status = "finished";
  //   });
  // }
});
</script>

<style lang="scss" scoped></style>
